package com.zyb.lmbackend.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zyb.lmbackend.entity.CategoryDict;
import com.zyb.lmbackend.entity.GoodsBack;
import com.zyb.lmbackend.llm.LlmClient;
import com.zyb.lmbackend.llm.model.ClsResult;
import com.zyb.lmbackend.mapper.GoodsBackClassifiedMapper;
import com.zyb.lmbackend.mapper.GoodsBackMapper;
import com.zyb.lmbackend.service.CategoryDictService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;
/**
 * 单条重分类控制器。
 *
 * 用于按 SN 重新走一遍 LLM 分类流程（便于修正个别样本）。
 */

@RestController
@RequestMapping("/api/reclassify")
public class ReclassifyController {

    private final GoodsBackMapper goodsBackMapper;
    private final GoodsBackClassifiedMapper classifiedMapper;
    private final CategoryDictService categoryDictService;
    private final LlmClient llmClient;

    public ReclassifyController(GoodsBackMapper goodsBackMapper,
                                GoodsBackClassifiedMapper classifiedMapper,
                                CategoryDictService categoryDictService,
                                LlmClient llmClient) {
        this.goodsBackMapper = goodsBackMapper;
        this.classifiedMapper = classifiedMapper;
        this.categoryDictService = categoryDictService;
        this.llmClient = llmClient;
    }

    @Operation(summary = "Reclassify one SN")
    @PostMapping("/by-sn")
    /**
     * 按 SN 重新分类并写回 goods_back_classified（UPSERT）。
     */
    public ResponseEntity<Void> bySn(@RequestParam String sn, @RequestParam(required = false) Integer taskVersion) {
        GoodsBack g = goodsBackMapper.selectBySn(sn);
        if (g == null) return ResponseEntity.notFound().build();
        List<String> allowed = categoryDictService.list(new LambdaQueryWrapper<CategoryDict>().eq(CategoryDict::getIsActive, (byte) 1))
                .stream().map(CategoryDict::getCode).collect(Collectors.toList());
        List<ClsResult> res = llmClient.classifyBatch(List.of(g.getBackDetail()), allowed);
        if (!res.isEmpty()) {
            ClsResult r = res.get(0);
            int version = taskVersion == null ? 1 : taskVersion;
            // UPSERT 写回明细
//            这里把大模型的分类后信息更新到被前端直接查的那张表
            classifiedMapper.upsert(g.getSn(), g.getBackDetail(), r.getCategoryCode(), r.getConfidence(), r.getReason(), "dashscope", version);
        }
        return ResponseEntity.ok().build();
    }
}
